package com.jcfk.system.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.business.enums.AvailableStatus;
import com.jcfk.common.business.enums.DeleteFlag;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.cache.redis.service.RedisHashService;
import com.jcfk.common.core.security.JwtUtil;
import com.jcfk.common.security.service.TokenService;
import com.jcfk.common.web.constant.SecurityConstants;
import com.jcfk.common.web.domain.LoginInfo;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.common.web.domain.TokenInfo;
import com.jcfk.common.web.utils.ServletUtils;
import com.jcfk.system.dao.LoginDao;
import com.jcfk.system.domain.dto.PersonLoginRequest;
import com.jcfk.system.domain.po.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录 业务逻辑
 *
 * @author 李炳海
 */
@Service
public class PersonLoginService extends BaseService<LoginDao, SysUser> {

    private static Logger logger = LoggerFactory.getLogger(PersonLoginService.class);

    /**
     * tokenService
     */
    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisHashService redisHashService;

    /**
     * 登录
     *
     * @param loginParameter 登录参数
     * @return RetResult
     */
    public RetResult<TokenInfo> login(PersonLoginRequest loginParameter) {
        if (StrUtil.isEmpty(loginParameter.getApplicationType())) {
            loginParameter.setApplicationType("pcWeb");
        }

        TokenInfo tokenInfo = new TokenInfo();
        // 校验员工号
        if (StrUtil.isEmpty(loginParameter.getMemberEmpNo())) {
            return RetResult.fail("员工号不能为空");
        }

        // 查询系统用户
        SysUser user = this.getByEmpNo(loginParameter.getMemberEmpNo());
        if (user == null) {
            return RetResult.fail("员工号不正确");
        }

        if (user.getEnabled().equals(0)) {
            return RetResult.fail("用户已停用");
        }

        if (user.getEnabled().equals(AvailableStatus.ENABLE)) {
            return RetResult.fail("用户未启用");
        }

        // 设置登录信息
        LoginInfo loginUser = new LoginInfo();
        loginUser.setUserId(user.getId());
        loginUser.setLoginName(user.getLoginName());
        loginUser.setUserName(user.getFirstName());
        loginUser.setLoginTime(new Date());
        loginUser.setApplicationType(loginParameter.getApplicationType());
        loginUser.setUserType(user.getUserType());
        loginUser.setParameters(loginParameter.getParameters());
        loginUser.getParameters().put("empNo",loginParameter.getMemberEmpNo());
        String token = tokenService.createLogin(loginUser);
        loginUser.setToken(token);

        // 设置token
        tokenInfo.setStatus(true);
        tokenInfo.setAccessToken(token);

        // 设置用户权限
        Map<String, String> powerCodeMap = new HashMap<>();
        redisHashService.setMap(SecurityConstants.LOGIN_POWER_HEADER + token, powerCodeMap);
        redisHashService.expire("", loginUser.getExpirationMinute(), TimeUnit.MINUTES);

        // 获取客户端IP
        HttpServletRequest request = ServletUtils.getRequest();
        String ip = "127.0.0.1";
        if (request != null) {
            ip = ServletUtils.getClientRequestIp(request);
        }
        return RetResult.ok(tokenInfo);
    }

    /**
     * 通过员工号获取用户信息
     *
     * @param empNo
     * @return
     */
    public SysUser getByEmpNo(String empNo) {
        // 查询条件
        QueryWrapper<SysUser> qw = new QueryWrapper<>();
        qw.lambda().eq(SysUser::getDeleted, DeleteFlag.NOTDELETED);
        qw.lambda().eq(SysUser::getEmpNo, empNo);
        SysUser user = super.getOne(qw);

        // 查询数据
        return user;
    }

    /**
     * 生成token
     *
     * @param loginUser 登录信息
     * @return token
     */
    private String createToken(LoginInfo loginUser) {
        String token = "";
        try {
            token = JwtUtil.createToken(loginUser.getUserId(), loginUser.getUserName());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return token;
    }

}
